import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { Season } from "@/type/game";
import { useUserStore } from "./userStore";
import { SceneType, useSceneStore } from "./sceneStore";
import { useMapStore } from "./mapStore";
import { loadMap, renderMap } from "@/utils/map";

// 星期枚举
export enum Weekday {
  Monday = "星期一",
  Tuesday = "星期二",
  Wednesday = "星期三",
  Thursday = "星期四",
  Friday = "星期五",
  Saturday = "星期六",
  Sunday = "星期日",
}

const TIME_STORAGE_KEY = "xinglu-valley-game-time";

export const useTimeStore = defineStore("time", () => {
  const loadSavedTime = () => {
    const savedTime = localStorage.getItem(TIME_STORAGE_KEY);
    if (savedTime) {
      try {
        const parsedTime = JSON.parse(savedTime);
        parsedTime.season =
          parsedTime.season in Season ? parsedTime.season : Season.SPRING;
        parsedTime.weekday =
          parsedTime.weekday in Weekday ? parsedTime.weekday : Weekday.Monday;
        return parsedTime;
      } catch (error) {
        console.error("加载游戏时间失败：", error);
      }
    }
    return {
      hours: 6, // 游戏开始时间为早上6点
      minute: 0, // 分钟
      day: 1, // 天数
      season: Season.SPRING, // 季节
      weekday: Weekday.Monday, // 星期
      year: 2025, // 年份
      paused: false, // 游戏是否暂停
      timeScale: 0.7, // 游戏时间流逝速度，0.7表示现实中0.7秒对应游戏中1分钟
    };
  };

  // 时间系统状态
  const gameTime = ref(loadSavedTime());

  // 保存时间
  const saveGameTime = () => {
    localStorage.setItem(TIME_STORAGE_KEY, JSON.stringify(gameTime.value));
  };

  // 格式化时间
  const formattedTime = computed(() => {
    const hours = gameTime.value.hours.toString().padStart(2, "0");
    const minute = gameTime.value.minute.toString().padStart(2, "0");
    return `${hours}:${minute}`;
  });

  let lastUpdateTime = Date.now();
  let accumulatedTime = 0; // 累积时间

  /**
   * 更新游戏时间
   */
  const updateGameTime = () => {
    if (gameTime.value.paused) {
      lastUpdateTime = Date.now();
      return;
    }

    const currentTime = Date.now();
    const realTimeDelta = (currentTime - lastUpdateTime) / 1000; // 实际经过的秒数
    lastUpdateTime = currentTime;

    // 累积时间
    accumulatedTime += realTimeDelta;

    // 计算游戏经过的分钟数（使用累积时间）
    const gameMinutesPassed = Math.floor(
      accumulatedTime / gameTime.value.timeScale
    );

    // 如果有分钟变化
    if (gameMinutesPassed > 0) {
      // 更新游戏时间
      updateMinutes(gameMinutesPassed);
      // 减去已经使用的累积时间
      accumulatedTime -= gameMinutesPassed * gameTime.value.timeScale;
      saveGameTime();
    }

    checkPlayerLocation();
  };

  const updateMinutes = (minutes: number) => {
    // 更新分钟
    let newMinute = gameTime.value.minute + minutes;
    let hourIncrement = Math.floor(newMinute / 60);
    newMinute %= 60;

    // 更新小时
    if (hourIncrement > 0) {
      updateHours(hourIncrement);
    }

    gameTime.value.minute = newMinute;
  };

  // 更新小时
  const updateHours = (hours: number) => {
    let newHour = gameTime.value.hours + hours;

    // 检查是否超过了一天（超过凌晨2点）
    if (newHour >= 26) {
      // 得到完整天数
      const daysToAdd = Math.floor((newHour - 6) / 20);
      newHour = 6 + ((newHour - 6) % 20);
      // 更新天数
      updateDay(daysToAdd);
    } else if (newHour >= 2 && newHour < 6) {
      // 如果时间在凌晨2:00到6:00之间，直接跳到6:00（新的一天开始）
      newHour = 6;
      updateDay(1);
    }

    // 超过24小时的显示为0-2点
    if (newHour >= 24) {
      newHour -= 24;
    }

    gameTime.value.hours = newHour;
  };

  // 更新天数
  const updateDay = (day: number) => {
    let newDay = gameTime.value.day + day;
    const weekdayValues = Object.values(Weekday);
    let currentWeekdayIndex = weekdayValues.indexOf(gameTime.value.weekday);
    let newWeekdayIndex = (currentWeekdayIndex + day) % weekdayValues.length;

    gameTime.value.weekday = weekdayValues[newWeekdayIndex];

    console.log("gameTime.value.weekday", gameTime.value.weekday);

    // 检查是否超过了季节
    if (newDay > 28) {
      // 得到完整的季节数
      const seasonsToAdd = Math.floor((newDay - 1) / 28);
      newDay = ((newDay - 1) % 28) + 1;

      updateSeasons(seasonsToAdd);
    }

    gameTime.value.day = newDay;

    // const weatherStore = useWeatherStore();
    // weatherStore.checkWeatherRules();
  };

  // 更新季节
  const updateSeasons = (seasons: number) => {
    const seasonValues = Object.values(Season);
    let currentSeasonIndex = seasonValues.indexOf(gameTime.value.season);

    // 计算新的季节索引
    let newSeasonIndex = (currentSeasonIndex + seasons) % 4;

    // 计算年份变化
    const yearsToAdd = Math.floor((currentSeasonIndex + seasons) / 4);

    // 更新季节
    gameTime.value.season = seasonValues[newSeasonIndex];

    if (yearsToAdd > 0) {
      gameTime.value.year += yearsToAdd;
    }
  };

  /**
   * 暂停/继续游戏时间
   */
  const togglePause = () => {
    gameTime.value.paused = !gameTime.value.paused;
    lastUpdateTime = Date.now(); // 重置上次更新时间
  };

  // 计算当前时间段的亮度系数 (0-1)
  const brightnessFactor = computed(() => {
    const hour = gameTime.value.hours;
    const minute = gameTime.value.minute;
    const totalMinutes = hour * 60 + minute; // 将时间转换为分钟数

    // 日出时间
    const sunriseStart = 6 * 60;
    // 日落开始时间
    const sunsetStart = 18 * 60;
    // 完全天黑时间
    const nightStart = 20 * 60;
    // 午夜时间
    const midnight = 24 * 60;

    // 日出阶段
    if (totalMinutes >= 5 * 60 && totalMinutes < 7 * 60) {
      const progress = (totalMinutes - 5 * 60) / 120;
      // 0.2是基础亮度，0.8是增幅亮度
      return 0.2 + 0.8 * Math.pow(progress, 2); // 使用二次方曲线使日出更自然
    }
    // 白天
    else if (totalMinutes >= 7 * 60 && totalMinutes < 17 * 60) {
      return 1.0;
    }
    // 日落阶段
    else if (totalMinutes >= 17 * 60 && totalMinutes < nightStart) {
      const progress = (totalMinutes - 17 * 60) / 180;
      return 1.0 - Math.pow(progress, 1.5) * 0.7;
    }
    // 夜晚
    else {
      return 0.3;
    }
  });

  // 检查玩家位置
  const checkPlayerLocation = async () => {
    const userStore = useUserStore();
    const sceneStore = useSceneStore();
    const mapStore = useMapStore();

    if (loadSavedTime().hours === 21 && loadSavedTime().minute === 20) {
      if (sceneStore.currentScene !== SceneType.HOUSE) {
        userStore.baseStats.energy = 0;
        sceneStore.setCurrentScene(SceneType.HOUSE);
        sceneStore.changeScene(SceneType.HOUSE, { x: 640, y: 540 });
        if (mapStore.currentCtx && mapStore.currentMap) {
          const mapPath =
            sceneStore.currentScene === SceneType.FARM
              ? "/src/assets/maps/baseMap.json"
              : "/src/assets/maps/farmHouse.json";
          const map = await loadMap(mapPath);
          mapStore.updateMapData(map);
          renderMap(mapStore.currentCtx, mapStore.currentMap);
        }
      }
    }
  };

  return {
    gameTime,
    togglePause,
    formattedTime,
    loadSavedTime,
    updateGameTime,
    updateDay,
    brightnessFactor,
  };
});
